﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YJ_App.Tool.Image;
using YJ_App.Tool.Log;
using YJ_Code.Entities.Topic;
using YJ_Code.Entities.User;
using YJ_Code.Enums;
using YJ_Code.Tool;
using YJ_Core.Entities.Common;
using YJ_Core.Entities.Utils;
using YJ_Core.Tool.Token;
using static YJ_App.Admin_System.Dtos.TopicAdminDto;
using static YJ_App.Applet.Dtos.AppletHomeDto;

namespace YJ_App.Applet.Service
{
    /// <summary>
    /// 小程序首页服务
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.AppletHome, Name = "AppletHome")]
    public class AppletHomeService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogService _logService;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AppletHomeService(ISqlSugarClient db, ILogService logService)
        {
            _db = db;
            _logService = logService;
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> IssueTopic(IssueTopicInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.Title))
            {
                throw Oops.Bah("请输入标题");
            }
            if (string.IsNullOrWhiteSpace(input.Content))
            {
                throw Oops.Bah("请输入描述内容");
            }

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            var guid = Guid.NewGuid().ToString("N");
            try
            {
                int addCount = await _db.Insertable(new Topics
                {
                    Content = input.Content,
                    Address = input.Address,
                    Latitude = input.Latitude,
                    Longitude = input.Longitude,
                    LocationName = input.LocationName,
                    Status = 1,
                    Title = input.Title,
                    TopicId = guid,
                    UserId = user.UserId,
                    CreateMan = user.UserName,
                    IsDelete = false,
                    CreateTime = DateTime.Now,
                    CheckStatus = 0,
                    Email = user.Email,
                    LikeCount = 0,
                    CollectCount = 0,
                    ShareCount = 0,
                    SkimThroughCount = 0,
                }).ExecuteCommandAsync();
                if (addCount < 1)
                {
                    throw Oops.Bah("发布失败【Topics】");
                }

                // 图片
                if (input.Images.Count > 0)
                {
                    var addImageCount = 0;
                    // 遍历新增图片
                    foreach (var item in input.Images)
                    {
                        int imageCount = await _db.Insertable(new Images
                        {
                            Id = Guid.NewGuid().ToString("N"),
                            Code = guid,
                            Type = "Issue",
                            Url = item,
                            IsDelete = false,
                            CreateMan = user.UserName,
                            CreateTime = DateTime.Now,

                        }).ExecuteCommandAsync();

                        addImageCount += imageCount;
                    }
                    if (addImageCount != input.Images.Count)
                    {
                        throw Oops.Bah("发布失败,图片上传数量与添加不一致【Images】");
                    }
                }

                // 发布日志
                await _logService.AddLog(new LogDto.AddLogInput
                {
                    TopicId = guid,
                    Type = "发布",
                    UserName = user.UserName,
                    Content = "话题已提交至审核系统等待处理"
                });


            }
            catch (Exception ex)
            {

                throw Oops.Bah("发布接口异常", ex); ;
            }

            return new ResponseStatus { Message = "发布成功，等待系统审核，即将返回首页", StatusCode = 200 };
        }

        /// <summary>
        /// 首页话题列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<AppletSelectHomeTopicListResp> AppletSelectHomeTopicList(AppletSelectHomeTopicListInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey();

            RefAsync<int> total = 0;
            var list = await _db.Queryable<Topics>()
                .Where((t1) => t1.CheckStatus == 1 && t1.Status == 1)
                .Select((t1) => new AppletSelectHomeTopicListOutput
                {
                    Title = t1.Title,
                    Status = t1.Status,
                    UserId = t1.UserId,
                    Address = t1.Address,
                    Content = t1.Content,
                    TopicId = t1.TopicId,
                    Latitude = t1.Latitude,
                    LikeCount = t1.LikeCount,
                    Longitude = t1.Longitude,
                    ShareCount = t1.ShareCount,
                    CreateTime = t1.CreateTime,
                    CheckStatus = t1.CheckStatus,
                    LocationName = t1.LocationName,
                    CollectCount = t1.CollectCount,
                    SkimThroughCount = t1.SkimThroughCount,
                })
                //.OrderBy(it => SqlFunc.GetRandom())
                .OrderByDescending(it => it.CreateTime)
                .ToPageListAsync(input.Page, input.PageSize, total);

            // 获取图片
            var images = await _db.Queryable<Images>()
                .Where(it => list.Select(it => it.TopicId).Contains(it.Code)).ToListAsync();

            var userInfo = await _db.Queryable<UserInfo>()
                .Where(it => it.State && list.Select(it => it.UserId).Contains(it.UserId)).ToListAsync();

            var takeNotes = await _db.Queryable<TakeNotes>()
                .Where(it => list.Select(it => it.TopicId).Contains(it.TopicId)).ToListAsync();

            foreach (var item in list)
            {
                item.Image = images.FirstOrDefault(it => it.Code == item.TopicId)?.Url ?? "";
                item.Email = userInfo.FirstOrDefault(it => it.UserId == item.UserId).Email ?? "";
                item.HeadPortraitPath =
                    userInfo.FirstOrDefault(it => it.UserId == item.UserId).HeadPortraitPath ?? "";
                item.NickName = userInfo.FirstOrDefault(it => it.UserId == item.UserId).NickName ?? "";
                item.UserName = userInfo.FirstOrDefault(it => it.UserId == item.UserId).UserName ?? "";

                item.IsLiked = takeNotes.Any(it =>
                it.TopicId == item.TopicId
                && it.Type == (int)TopicTakeNotesTypeEnumsCode.DZ
                && it.UserId == user.UserId);
            }

            return new AppletSelectHomeTopicListResp
            {
                List = list,
                Total = total,
                Message = "OK",
                StatusCode = 200
            };
        }

        /// <summary>
        /// 话题点赞
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> AppletTopicDZ(TopicDZInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            if (string.IsNullOrWhiteSpace(input.TopicId) || string.IsNullOrWhiteSpace(input.UserId))
            {
                throw Oops.Bah("id入参异常");
            }

            try
            {
                var topic = await _db.Queryable<Topics>()
               .FirstAsync(it => it.TopicId == input.TopicId) ?? throw Oops.Bah("话题信息异常");

                var userInfo = await _db.Queryable<UserInfo>()
                    .FirstAsync(it => it.UserId == input.UserId) ?? throw Oops.Bah("用户信息异常");


                // 取消点赞删除一条记录
                if (input.IsLiked.HasValue && input.IsLiked == false)
                {
                    var takeNotes = await _db.Queryable<TakeNotes>()
                         .FirstAsync(it =>
                         it.TopicId == input.TopicId
                         && it.UserId == input.UserId
                         && it.Type == (int)TopicTakeNotesTypeEnumsCode.DZ);

                    // 软删除
                    takeNotes.IsDelete = true;
                    int updateCount = await _db.Updateable(takeNotes)
                        .WhereColumns(it => it.Id)
                        .UpdateColumns(it => new
                        {
                            it.IsDelete
                        }).ExecuteCommandAsync();
                    if (updateCount < 1)
                    {
                        throw Oops.Bah("取消点赞异常");
                    }

                    // 点赞数量-1
                    topic.LikeCount -= 1;
                    await _db.Updateable(topic)
                        .WhereColumns(it => it.TopicId)
                        .UpdateColumns(it => new
                        {
                            it.LikeCount
                        }).ExecuteCommandAsync();

                }
                else
                {
                    // 添加记录
                    int count = await _db.Insertable(new TakeNotes
                    {
                        Id = Guid.NewGuid().ToString("N"),
                        TopicId = input.TopicId,
                        Type = (int)TopicTakeNotesTypeEnumsCode.DZ,
                        UserId = input.UserId,
                        CreateMan = user.UserName,
                        CreateTime = DateTime.Now,
                    }).ExecuteCommandAsync();

                    if (count < 1)
                    {
                        throw Oops.Bah("操作异常");
                    }

                    // 点赞数量+1
                    topic.LikeCount += 1;
                    await _db.Updateable(topic)
                        .WhereColumns(it => it.TopicId)
                        .UpdateColumns(it => new
                        {
                            it.LikeCount
                        }).ExecuteCommandAsync();
                }
                return new ResponseStatus { Message = "操作成功", StatusCode = 200 };
            }
            catch (Exception ex)
            {

                throw Oops.Bah("操作异常", ex);
            }



        }

        /// <summary>
        /// 校验敏感词
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> AppletVerifySensitiveWord(AppletVerifySensitiveWordInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            var sens = await _db.Queryable<SensitiveWords>()
                .Where(it => it.IsEnabled).ToListAsync();

            // 输入包含数据
            var title = sens.FirstOrDefault(it => input.Title.Contains(it.Word));

            if (title != null)
            {
                throw Oops.Bah($"标题中包含有敏感词【{title.Word}】，发布失败");
            }

            var content = sens.FirstOrDefault(it => input.Content.Contains(it.Word));
            if (content != null)
            {
                throw Oops.Bah($"内容中包含有敏感词【{content.Word}】，发布失败");
            }

            return new ResponseStatus
            {
                Message = "ok",
                StatusCode = 200
            };
        }

        /// <summary>
        /// 存草稿
        /// </summary>
        /// <returns></returns>
        //public async Task<ResponseStatus> ExistDraft(ExistDraftInput input)
        //{
        //    //去掉入参前后空格
        //    ToolHelper.TrimStrings(input);
        //    // 获取操作用户的信息
        //    var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");


        //}
    }
}
